import { Injectable } from '@angular/core';
import { CoreModule } from '../core.module';

@Injectable({
  providedIn: 'root'
})
export class StorageService {

  private localStorage: Storage;

  public set(key: string, value: string | number | object): void {
    if (typeof value === 'string') {
      this.localStorage.setItem(key, value);
    } else if (typeof value === 'number') {
      this.localStorage.setItem(key, value + '');
    } else {
      this.localStorage.setItem(key, JSON.stringify(value));
    }
  }

  public get<T>(key: string): T | null {
    const value = this.localStorage.getItem(key);
    if (value) {
      // 可能存在隐患
      const result = JSON.parse(value);
      return result;
    } else {
      return null;
    }
     
  }

  public remove(key: string): void {
    this.localStorage.removeItem(key);
  }

  public clear() {
    this.localStorage.clear();
  }

  constructor() {
    if (!localStorage) {
      throw new Error('Current browser does not support Local Storage');
    }
    this.localStorage = localStorage;
  }
}
